import React from 'react';
import {Button , Form , Row, Col , Cascader ,message} from 'antd'
import AppHelper from 'utils/AppHelper'
import HttpUtils from 'utils/HttpUtils'

class SearchForm extends React.Component {


	lastSearhParams = {}

	constructor(props){
		super(props)
	}

	state = {
		categories : []
	}

	handleReset = () => {
		this.props.form.resetFields();
	}

	reload(){
		let self = this;
		HttpUtils.listSpecs( this.lastSearhParams , {
			success (resp) {
				self.props.receiveData(resp.data);
			}
		})
	}

	handleSearch (e) {
		e.preventDefault()
		this.props.changeLoading(true);
		let catIds = this.props.form.getFieldsValue()['catId'];
		let catId = catIds && catIds[catIds.length - 1]
		let params = {}
		if(catId){
			params.catId = catId
		}
		let self = this;
		this.lastSearhParams = params
		HttpUtils.listSpecs( params , {
			success (resp) {
				self.props.receiveData(resp.data);
			}
		})
	}

	componentDidMount(){
		message.info('Loading...')
		let self = this;
        HttpUtils.listCategories({
            success(resp){
                let categories = AppHelper.tools.formatCategories(resp.data , true);
                self.setState({categories});
            }
        });

        HttpUtils.listSpecs( {} , {
			success (resp) {
				self.props.receiveData(resp.data);
				message.destroy()
			}
		})

		this.props.setSearchForm(this)
	}

	render () {
		const {getFieldDecorator} = this.props.form;
		const formItemLayout = {
	      labelCol: { span: 3 },
	      wrapperCol: { span: 21 },
	    };
		return (
			<Form className="ant-advanced-search-form" onSubmit={(e) => this.handleSearch(e)}>
				<Row gutter={24}>
					<Col span={8} style={{ display: 'block'}}>
						<Form.Item {...formItemLayout} label="分类" >
                            {getFieldDecorator('catId')(
                                <Cascader placeholder='按分类查找' options={this.state.categories} changeOnSelect/>
                            )}
                        </Form.Item>
	                </Col>
                </Row>
                <Row>
                	<Col span={24} style={{ textAlign: 'right' }}>
			            <Button type="primary" htmlType="submit">Search</Button>
			            <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
			              Clear
			            </Button>
			        </Col>
                </Row>
			</Form>

			)
	}
}

const SpecSearchForm = Form.create()(SearchForm);
export default SpecSearchForm;
